<template>
  <div class="wechat-messages">
    <el-card>
      <div slot="header" class="header">
        <span>消息发送记录</span>
        <div>
          <el-button size="small" @click="refreshAll" :loading="loading">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            inactive-text="手动刷新"
            @change="toggleAutoRefresh"
          />
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon total">
                  <i class="el-icon-message"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.total || 0 }}</div>
                  <div class="stat-label">总发送</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon success">
                  <i class="el-icon-success"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.success || 0 }}</div>
                  <div class="stat-label">成功</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon failed">
                  <i class="el-icon-error"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.failed || 0 }}</div>
                  <div class="stat-label">失败</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon rate">
                  <i class="el-icon-pie-chart"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.success_rate || 0 }}%</div>
                  <div class="stat-label">成功率</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="filters">
        <el-select v-model="filters.send_status" placeholder="发送状态" style="width: 120px;">
          <el-option label="全部" value="" />
          <el-option label="待发送" :value="0" />
          <el-option label="已发送" :value="1" />
          <el-option label="发送失败" :value="2" />
        </el-select>
        <el-button type="primary" @click="fetchMessages">筛选</el-button>
      </div>

      <el-table :data="messages" v-loading="loading">
        <el-table-column prop="user_open_id" label="接收者" show-overflow-tooltip />
        <el-table-column prop="message_type" label="消息类型">
          <template slot-scope="scope">
            {{ getMessageTypeName(scope.row.message_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="消息内容" show-overflow-tooltip />
        <el-table-column prop="send_status" label="发送状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.send_status)">
              {{ getStatusName(scope.row.send_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="send_time" label="发送时间" />
        <el-table-column prop="error_message" label="错误信息" show-overflow-tooltip />
      </el-table>

      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.limit"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'WechatMessages',
  data() {
    return {
      messages: [],
      loading: false,
      autoRefresh: false,
      refreshTimer: null,
      stats: {
        total: 0,
        success: 0,
        failed: 0,
        success_rate: 0
      },
      filters: {
        send_status: ''
      },
      pagination: {
        page: 1,
        limit: 20,
        total: 0
      }
    }
  },
  mounted() {
    this.fetchMessages()
    this.fetchStats()
    
    // 监听全局事件，当有消息发送时刷新
    this.$root.$on('messageSent', () => {
      this.refreshAll()
    })
  },
  
  beforeDestroy() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
    
    // 移除全局事件监听
    this.$root.$off('messageSent')
  },
  methods: {
    async fetchMessages() {
      this.loading = true
      try {
        const response = await axios.get('/nfc/wechat/messages', {
          params: {
            page: this.pagination.page,
            limit: this.pagination.limit,
            send_status: this.filters.send_status
          }
        })
        this.messages = response.data.data.data
        this.pagination.total = response.data.data.total
      } catch (error) {
        this.$message.error('获取消息记录失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchStats() {
      try {
        const response = await axios.get('/nfc/wechat/stats')
        // 正确解析嵌套的消息统计数据
        this.stats = response.data.data.message_stats
      } catch (error) {
        console.error('获取统计失败:', error)
      }
    },
    
    handlePageChange(page) {
      this.pagination.page = page
      this.fetchMessages()
    },
    
    getMessageTypeName(type) {
      const types = {
        1: '文本消息',
        2: '图片消息',
        3: '图文消息',
        4: '模板消息'
      }
      return types[type] || '未知'
    },
    
    getStatusName(status) {
      const statuses = {
        0: '待发送',
        1: '已发送',
        2: '发送失败'
      }
      return statuses[status] || '未知'
    },
    
    getStatusType(status) {
      const types = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return types[status] || 'info'
    },
    
    // 刷新所有数据
    refreshAll() {
      this.fetchMessages()
      this.fetchStats()
    },
    
    // 专门供外部调用的刷新方法
    refreshMessages() {
      this.refreshAll()
    },
    
    // 切换自动刷新
    toggleAutoRefresh() {
      if (this.autoRefresh) {
        // 开启自动刷新，每30秒刷新一次
        this.refreshTimer = setInterval(() => {
          this.refreshAll()
        }, 30000)
      } else {
        // 关闭自动刷新
        if (this.refreshTimer) {
          clearInterval(this.refreshTimer)
          this.refreshTimer = null
        }
      }
    }
  }
}
</script>

<style scoped>
/* 统计卡片样式 - 参考优惠券记录页面设计 */
.statistics-cards {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 24px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.failed {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.filters {
  margin-bottom: 20px;
}

.filters > * {
  margin-right: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header > div {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>